package com.fubowen.lepton.ui.reader.book.impl

import com.fubowen.lepton.bean.BookChapterBean
import com.fubowen.lepton.extension.trimChar
import com.fubowen.lepton.ui.reader.book.IBook
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.io.File

class FileBook(
    override var url: String,
    override var onCompleted: IBook.() -> Unit = {}
) : IBook {
    override val chapterList = mutableListOf<BookChapterBean>()
    override var errMsg: String? = null
    override var onProgressChanged: (BookChapterBean) -> Unit = {}
    override var isGetCatalogState = false
    override var name = ""

    private lateinit var file: File

    override fun tryGet() {
        val that = this
        CoroutineScope(Dispatchers.IO).launch {
            file = File(this@FileBook.url)
            if (file.exists()) {
                if (file.isFile) {
                    tryGetCatalog()
                } else {
                    errMsg = "${this@FileBook.url} 不是一个文件，无法读取"
                }
            } else {
                errMsg = "${this@FileBook.url} 文件不存在"
            }
            onCompleted(that)
        }
    }

    override fun tryGetCatalog() {
        val regex = Regex("(?<!\\p{IsHan})(第[一二三四五六七八九十百千万零\\d]+章)\\s*(.+)\\s*$")
        var chapterOrder = 1
        var chapter: BookChapterBean? = null
        val chapterContent = StringBuilder()
        var isContentStart = false
        tryGetName()
        file.bufferedReader().useLines { lines ->
            lines.forEach { item ->
                val result = regex.find(item)
                var isTitle = false
                if (result != null) {
                    isContentStart = true
                    isGetCatalogState = true
                    chapter?.let {
                        it.content = chapterContent.toString()
                        it.words = it.content.length
                        chapterList.add(it)
                        onProgressChanged(it)
                    }
                    val name = result.groupValues[2].trimChar() ?: ""
                    chapter = BookChapterBean(
                        name = name,
                        order = chapterOrder++,
                        isDownload = false
                    )
                    chapterContent.setLength(0)
                    isTitle = true
                }
                if (isContentStart && !isTitle) {
                    chapterContent.appendLine(item)
                }
            }
        }
    }

    override fun tryGetName() {
        name = file.nameWithoutExtension
    }

    override fun tryGetUrl() {}
}